package Model

import (
	"database/sql"
	"gin/Config"
	"github.com/gin-gonic/gin"
	"log"
)

type Login struct {
	Id         int    `json:"id"`
	Text       string `json:"text"`
	Password   string `json:"password"`
	CreateTime int    `json:"create_time"`
	UpdateTime int    `json:"update_time"`
}

// 登录成功
func (l *Login) Login(c *gin.Context) {
	var result string

	err := datebles.InitDB().QueryRow("SELECT text FROM login WHERE text = ? AND password = ?", l.Text, l.Password).Scan(&result)
	if err != nil {

		//判断是否查到当前行
		if err == sql.ErrNoRows {
			Html(c, "密码错误！", "login")
		} else {
			Html(c, "数据库查询错误!", "login")
		}
		return
	}
	Html(c, "登录成功！", "index")
}

// 注册功能
func (l *Login) Register(c *gin.Context) {
	var oneInfo string
	err := datebles.InitDB().QueryRow("select text from login where text = ?", l.Text).Scan(&oneInfo)
	if err == sql.ErrNoRows {
		// 账号不存在，执行数据库插入操作
		_, err := datebles.InitDB().Exec("INSERT INTO login (text, password, create_time, update_time) VALUES (?, ?, ?, ?)", l.Text, l.Password, l.CreateTime, l.UpdateTime)
		if err != nil {
			log.Println(err) // 错误日志记录
			Html(c, "注册失败！", "login")
			return
		}
		Html(c, "注册成功！", "index")
	} else if err != nil {
		log.Println(err) // 错误日志记录
		Html(c, "数据库查询错误！", "login")
	} else {
		Html(c, "账号已经存在！", "login")
	}
}

func Html(c *gin.Context, msg string, url string) {
	redirectURL := "http://127.0.0.1:8080/user/" + url // 跳转链接
	message := msg
	html := `
		<!DOCTYPE html>
		<html>
		<head>
			<script>
				if (confirm("` + message + `")) {
					window.location.href = "` + redirectURL + `";
				}else{
					window.location.href = "` + redirectURL + `";
				}
			</script>
		</head>
		<body>
		</body>
		</html>
		`
	c.Data(200, "text/html; charset=utf-8", []byte(html))
}
